import os
import time
import json
from pywinauto import Desktop
from selenium.webdriver.common.keys import Keys

from config.global_settings import ENTRY_DOWNLOAD_PATH, ARAP_URL, gx_username, gx_password, SHARE_URL, ARAP_URL
from yfys.original_robot import OriginalRobot
from zjbj.web_util.web_robot import WebRobot


class YfysRobot(OriginalRobot):
    def __init__(self, url, download_path):
        """
        初始化
        :param url: 八局url
        :param download_path: 附件/发票下载路径
        :param body: 填报信息
        """
        super().__init__(url, download_path)
        self.download_path = download_path
        self.url = url

    def run(self):
        # 清除之前下载的文件
        # self.clear_file()

        # 登录
        self.login()
        # RPA开始同步
        # self.start_sync()
        # 新增账龄预警数据
        # self.addAlert()

        # 导出文件
        # self.export()

        # 上传
        # self.upload()

        # self.getDataFromWebPage()

        # self.getDataFromJsonFile()

    def login(self):
        # 打开网页
        self.driver.get(self.url)
        # 输入用户名和密码
        self.fill_input('//input[@id="username"]', gx_username)
        self.fill_input('//input[@id="password"]', gx_password)
        self.click_element('//button[@class="ant-btn ant-btn-primary"]', mode='internal')
        time.sleep(1)

    def export(self):
        time.sleep(1)
        self.click_element('//a[contains(@href,"warning")]', mode='internal')
        time.sleep(0.5)
        self.click_element('//span[text()="导 出"]//parent::button', mode='internal')
        time.sleep(0.5)
        self.click_element('//span[text()="确 定"]//parent::button', mode='internal')

    def clear_file(self):
        """
        root  # 当前目录路径
        dirs  # 当前路径下所有子目录
        files  # 当前路径下所有非目录子文件
        :return:
        """
        for root, dirs, files in os.walk(self.download_path):
            if not files:
                return
            for file in files:
                dir_path = os.path.join(self.download_path, file)
                os.remove(dir_path)

    def upload(self):
        time.sleep(1)
        self.click_element('//span[text()="预算管理"]//parent::span//parent::div', mode='internal')
        self.click_element('//a[contains(@href,"budgetProgram")]', mode='internal')
        self.click_element('//span[text()="导入预算额"]//parent::button', mode='internal')
        time.sleep(0.5)
        self.click_element('//span[text()="上传完善后的表格文件"]//parent::button', mode='internal')

        # 输入文件名上传影像
        title = self.get_html_title()
        windows = Desktop(backend='uia')
        win = windows[f'{title} - Google Chrome']
        for root, dirs, files in os.walk(self.download_path):
            if not files:
                return
            for file in files:
                dir_path = os.path.join(self.download_path, file)
            if win.exists():
                editor = win.child_window(title="文件名(N):", control_type="Edit")
                editor.type_keys(dir_path, with_spaces=True)
                time.sleep(0.5)
                editor.type_keys("{ENTER}")
            time.sleep(1)
        self.click_element('//span[text()="确 定"]//parent::button', mode='internal')

    def get_html_title(self):
        title_xpath = 'html/head/title'
        ele = self.find_element(title_xpath)
        title = ele.get_attribute("textContent")
        return title

    def getDataFromWebPage(self):
        """
        从网页爬取数据
        :return:
        """
        self.click_element('//a[contains(@href,"confirmReview")]', mode='internal')
        # trs = self.driver.find_element_by_css_selector("table tr")
        tr_xpath = '//span[text()="序号"]/../../../../../../../../div[2]/table/tbody/tr'
        trs = self.find_elements(tr_xpath)
        # table tr
        data = []
        for i in range(len(trs)):
            confirm_review = {}
            for j in range(8):
                td = self.find_element(f"{tr_xpath}[{i + 1}]/td[{j + 1}]")
                # print(td.get_attribute('textContent'))
                if j == 0:
                    confirm_review['序号'] = td.get_attribute('textContent')
                elif j == 1:
                    confirm_review['流程编号'] = td.get_attribute('textContent')
                elif j == 2:
                    confirm_review['采购单号'] = td.get_attribute('textContent')
                elif j == 3:
                    confirm_review['确收金额(元)'] = td.get_attribute('textContent')
                elif j == 4:
                    confirm_review['审查状态'] = td.get_attribute('textContent')
                elif j == 5:
                    confirm_review['RPA状态同步'] = td.get_attribute('textContent')
                elif j == 6:
                    confirm_review['机器初审结果'] = td.get_attribute('textContent')
                elif j == 7:
                    confirm_review['操作'] = td.get_attribute('textContent')
                # elif j == 8:
                #     company['开户账户'] = td.get_attribute('textContent')
            data.append(confirm_review)

        print(data)
        names = json.dumps(data)
        self.filename = os.path.join(self.download_path, 'confirmReview.json')
        with open(self.filename, 'w') as file_obj:
            file_obj.write(json.dumps(data, ensure_ascii=False))

    def getDataFromJsonFile(self):
        """
        从json文件读取数据
        :return:
        """
        self.filename = os.path.join(self.download_path, 'names.json')
        with open(self.filename) as f:
            company_list = json.load(f)
        return company_list
        # for company_dict in company_list:
        #     print(company_dict['公司全称'])
        #     print(company_dict['公司简称'])
        #     print(company_dict['公司编码'])
        #     print(company_dict['公司类型'])
        #     print(company_dict['归属地'])
        #     print(company_dict['联系人'])
        #     print(company_dict['手机号'])
        #     print(company_dict['纳税人识别号'])
        #     print(company_dict['开户账户'])

    def addAlert(self):

        # 点击账龄预警超链接
        time.sleep(1)
        self.click_element('//a[contains(@href,"agingAlert")]', mode='internal')

        # 从Json文件中读取数据
        ys_list = self.getDataFromJsonFile()
        print(ys_list)

        for ys_dict in ys_list:
            # 点击新增按钮
            time.sleep(0.5)
            self.click_element('//span[text()="新 增"]//parent::button', mode='internal')

            time.sleep(1)
            # 输入客户编码
            self.fill_input("//input[@id = 'mold_series1']", ys_dict['khbm'])
            # 输入客户名称
            time.sleep(1)
            self.fill_input("//input[@id = 'mold_series2']", ys_dict['khmc'])
            # 输入合同号
            time.sleep(1)
            self.fill_input("//input[@id = 'mold_series3']", ys_dict['hth'])
            # 输入发票号
            time.sleep(1)
            self.fill_input("//input[@id = 'mold_series4']", ys_dict['fph'])
            # 输入发票日期
            time.sleep(1)
            self.click_element('//input[contains(@placeholder,"请选择发票日期")]', mode='internal')
            xpath = "//input[@class='ant-calendar-input ']"
            self.fill_input(xpath, ys_dict['fprq'])
            self.find_element(xpath).send_keys(Keys.ENTER)
            # 输入币种
            time.sleep(1)
            self.fill_input("//input[@id = 'mold_series6']", ys_dict['bz'])
            # 输入金额
            time.sleep(1)
            self.fill_input("//input[@id = 'mold_series7']", ys_dict['je'])
            # 输入到款日
            time.sleep(1)
            self.click_element('//input[contains(@placeholder,"请选择到款日")]', mode='internal')
            xpath = "//input[@class='ant-calendar-input ']"
            self.fill_input(xpath, ys_dict['dkr'])
            self.find_element(xpath).send_keys(Keys.ENTER)

            # 点击上传文件
            # 输入文件名上传影像
            self.click_element('//span[text()="点击上传"]//parent::button', mode='internal')
            title = self.get_html_title()
            windows = Desktop(backend='uia')
            win = windows[f'{title} - Google Chrome']
            for root, dirs, files in os.walk(self.download_path):
                if not files:
                    return
                for file in files:
                    dir_path = os.path.join(self.download_path, file)
                if win.exists():
                    editor = win.child_window(title="文件名(N):", control_type="Edit")
                    editor.type_keys(dir_path, with_spaces=True)
                    time.sleep(0.5)
                    editor.type_keys("{ENTER}")
                time.sleep(1)
            self.click_element('//span[text()="确 定"]//parent::button', mode='internal')

            self.click_element('//span[text() = "取 消"]/..', mode='internal')

    def get_html_title(self):
        title_xpath = 'html/head/title'
        ele = self.find_element(title_xpath)
        title = ele.get_attribute("textContent")
        return title

    def start_sync(self):
        time.sleep(1)
        self.click_element('//a[contains(@href,"confirmReview")]', mode='internal')

        # //button[@class="ant-btn ant-btn-primary RPA-button"]
        con = self.find_element('//button[@class="ant-btn ant-btn-primary RPA-button"]//span').get_attribute('textContent')
        if("RPA状态同步" == con):
            time.sleep(0.5)
            print(con)
            self.start_sync()
        else:
            print("123")


if __name__ == "__main__":
    if not os.path.exists(ENTRY_DOWNLOAD_PATH):
        os.mkdir(ENTRY_DOWNLOAD_PATH)
    DownLoadPath = os.path.join(ENTRY_DOWNLOAD_PATH, 'test')
    if not os.path.exists(DownLoadPath):
        os.mkdir(DownLoadPath)

    robot = YfysRobot(url=ARAP_URL, download_path=DownLoadPath)
    robot.run()
